<template>
    <div class="container">
        <el-row>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>知识管理</el-breadcrumb-item>
                <el-breadcrumb-item>心理测评管理</el-breadcrumb-item>
            </el-breadcrumb>
        </el-row>
        <el-row>
            <el-form :inline="true" :model="searchHeartMark" class="demo-form-inline">
                <el-form-item label="名称">
                    <el-input clearable @clear="queryList" v-model="searchHeartMark.name" placeholder="测评名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="queryList">查询</el-button>
                    <el-button type="success" icon="el-icon-plus" @click="clickAdd">新增测评</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row>
            <el-table :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }"
                :data="heartMarkList" border style="width: 100%">
                <el-table-column prop="id" label="ID">
                </el-table-column>
                <el-table-column prop="name" label="测评名称">
                </el-table-column>
                <el-table-column prop="simplyIntroduce" label="测评简介">
                </el-table-column>
                <el-table-column label="图片" width="130">
                    <template slot-scope="scope">
                        <el-image style="width: 100px; height: 55px"
                            :src="baseUrl + 'downLoad?filename=' + scope.row.img" :fit="'cover'"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="100">
                </el-table-column>
                <el-table-column prop="total" label="试题数量">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="clickEdit(scope.row)" icon="el-icon-edit" type="primary" size="mini">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteHeartMark(scope.row.id)"
                           >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <el-row>
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="searchHeartMark.pageNum" :page-sizes="[1, 5, 10, 20]"
                :page-size="searchHeartMark.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-row>
        <el-row>
            <el-dialog @close="clearData" :title="isadd ? '添加测评' : '修改测评'" :visible.sync="dialogFormVisible">
                <el-form :model="heartMark" ref="heartForm">
                    <el-form-item prop="name" :rules="[{ required: true, message: '测评名称不能为空', trigger: 'blur' }]" label="测评名称:"
                        :label-width="'90px'">
                        <el-input v-model="heartMark.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="测评简介:" :label-width="'90px'">
                        <el-input v-model="heartMark.simplyIntroduce" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="图片:" :label-width="'90px'">
                        <el-upload :action="baseUrl + 'upload'" list-type="picture-card" :file-list="fileList"
                            :on-preview="handlePictureCardPreview" :on-success="handleSuccess"
                            :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item v-if="isadd" label="添加试题:" :label-width="'90px'">
                        <!-- <div v-html="dong">

                        </div> -->
                        <el-button :disabled="!add ? true : false" @click="clickAddTest" type="plain"
                            icon="el-icon-plus">点击添加</el-button>&nbsp;<span style="color: #071a52"
                            v-if="testList != false">
                            已添加 <span style="color:#17b978; font-weight:600">{{ testList.length }}</span> 道试题
                        </span>
                    </el-form-item>

                    <el-form-item style="max-height: 200px;overflow-y:scroll" v-else label="试题:" :label-width="'80px'">
                        <span v-if="heartMark.heartTestList == false">无试题</span>
                        <el-collapse v-for="ts in heartMark.heartTestList" v-if="ts" accordion>
                            <el-collapse-item>
                                <template slot="title">
                                    <span style="font-size: medium; font-weight:600">{{ ts.title }}</span>
                                </template>
                                <span v-html="ts.content"></span>
                            </el-collapse-item>
                        </el-collapse>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="clearData">取 消</el-button>
                    <el-button v-if="isadd" type="primary" @click="addHeartMark">添 加</el-button>
                    <el-button v-else type="primary" @click="editHeartMark">修 改</el-button>
                </div>
            </el-dialog>
        </el-row>
        <el-row>
            <el-dialog :show-close="false" :visible.sync="testDialog">
                <el-row class="test-row">
                    <el-col :offset="1">
                        <el-button @click="addATest" type="primary" icon="el-icon-plus"
                            style="margin-right: 10px;">新增一条试题</el-button>
                    </el-col>
                </el-row>
                <el-row style="max-height: 400px; overflow-y:scroll;overflow-x:hidden;">
                    <el-row class="test-row" v-for="(item, index) in dongTestList" :key="index">
                        <el-form :model="item.test" ref="testForm" :rules="rules">
                            <el-form-item prop="title" :label="'题目' + (index + 1) + ':'" label-width="90px">
                                <el-input v-model="item.test.title" placeholder="请输入题目"></el-input>
                            </el-form-item>
                            <el-form-item prop="content" label="内容:" label-width="90px">
                                <quill-editor :options="editorOptions" v-model="item.test.content" resize="none"
                                    size="auto"></quill-editor>
                            </el-form-item>
                        </el-form>
                        <el-row>
                            <el-col :offset="19">
                                <el-button style="font-size: 12px;" @click="deleteATest(item)" icon="el-icon-delete"
                                    type="danger">删除题目{{ (index + 1) }}</el-button>
                            </el-col>
                        </el-row>
                    </el-row>
                </el-row>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="clearTestInfo">取 消</el-button>
                    <el-button type="primary" @click="addTestList">确 定</el-button>
                </div>
            </el-dialog>
        </el-row>
    </div>
</template>

<script>
import { url } from '@/util/tools';
import Vue from 'vue/dist/vue.esm.js';
export default {
    data() {
        return {
            heartMarkList: [],
            baseUrl: url,
            searchHeartMark: {
                name: '',
                pageNum: 1,
                pageSize: 10,
            },
            total: 0,
            //判断是否添加
            isadd: true,
            dialogFormVisible: false,
            heartMark: {
                name: '',
                simplyIntroduce: '',
                img: '',
                total: 0,
                heartTestList: []
            },
            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            // dong: '',
            add: true,
            // test: {
            //     title: '',
            //     content: ''
            // },
            testDialog: false,
            rules: {
                title: [{ required: true, message: '题目不能为空', trigger: 'blur' }],
                content: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
            },
            editorOptions: {
                modules: {
                    toolbar: [['bold', 'italic', 'underline', 'strike']],
                },
                placeholder: '请输入试题内容'
            },
            //要向数据库添加的试题列表
            testList: [],
            //动态试题
            dongTestList: [
                {
                    test: {
                        title: '',
                        content: '',
                    }

                }
            ],
        }
    },
    methods: {
        //点击编辑
        clickEdit(row) {
            console.log(row)
            this.heartMark = row
            this.dialogFormVisible = true
            this.isadd = false
            this.fileList = [{
                name: this.heartMark.img,
                url: this.baseUrl + 'downLoad?filename=' + this.heartMark.img
            }]
        },
        //编辑测评信息
        editHeartMark() {
            this.$http.put('heartMark', this.heartMark)
                .then(res => {
                    if (res.data.status == 200) {
                        this.queryList()
                        this.clearData()
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                    } else {
                        this.$message({
                            message: '修改失败',
                            type: 'error'
                        })
                    }
                })
                .catch(err => {
                    this.$message({
                        message: '请求异常',
                        type: 'error'
                    })
                })
        },

        //删除
        deleteHeartMark(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(`heartMark/${id}`)
                    .then(res => {
                        if (res.data.status == 200) {
                            this.$message({
                                type: 'success',
                                message: res.data.message
                            });
                            this.queryList()
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }

                    })
                    .catch(err => {
                        this.$message({
                            type: 'error',
                            message: '请求异常'
                        });
                    })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        //查询心理测评
        queryList() {
            this.$http.get('heartMark/page', { params: this.searchHeartMark })
                .then(res => {
                    if (res.data.status == 200) {
                        this.heartMarkList = res.data.data.list
                        this.total = res.data.data.total
                    } else {
                        this.$message({
                            message: '数据获取失败',
                            type: 'error'
                        })
                    }
                })
                .catch(err => {
                    this.$message({
                        message: '请求有误',
                        type: 'error'
                    })
                })
        },
        //添加心理测评
        addHeartMark() {
            console.log(this.testList)
            this.heartMark.heartTestList = this.testList
            this.$refs.heartForm.validate((valid) => {
                if (valid) {
                    this.$http.post('heartMark', this.heartMark)
                        .then(res => {
                            if (res.data.status == 200) {
                                this.queryList()
                                this.clearData()
                                this.$message({
                                    message: '添加成功',
                                    type: 'success'
                                })
                            } else {
                                this.$message({
                                    message: '添加失败',
                                    type: 'error'
                                })
                            }
                        })
                        .catch(err => {
                            this.$message({
                                message: '请求异常',
                                type: 'error'
                            })
                        })
                } else {
                    this.$message({
                        message: '测评名称不能为空，😜',
                        type: 'error'
                    })
                    return false;
                }
            });

        },

        //页面尺寸变化
        handleSizeChange(size) {
            this.searchHeartMark.pageSize = size
            this.queryList()
        },

        //页面选中
        handleCurrentChange(num) {
            this.searchHeartMark.pageNum = num
            this.queryList()
        },

        //文件上传前置操作
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //文件上传移除
        handleRemove() {
            this.fileList = []
            this.heartMark.img = ''
        },

        //点击新增按钮
        clickAdd() {
            this.isadd = true
            this.dialogFormVisible = true
        },
        //清除数据
        clearData() {
            this.heartMark = {
                name: '',
                simplyIntroduce: '',
                img: '',
                total: 0,
                heartTestList: []
            }
            this.fileList = []
            this.dialogImageUrl = ''
            this.dialogFormVisible = false
            this.add = true
            this.testList = []
            this.dongTestList = [
                {
                    test: {
                        title: '',
                        content: '',
                    }

                }
            ]
            if(this.isadd){
                this.$refs.heartForm.resetFields()
            }
        },

        //添加试题点击取消
        clearTestInfo() {
            this.$confirm('确定取消添加试题吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // this.test = {
                //     title: '',
                //     content: ''
                // }
                this.testDialog = false
                this.add = true
                // console.log(this.dongTestList.length)
                let len = this.dongTestList.length
                for (let index = 0; index < len; index++) {
                    this.$refs.testForm[index].resetFields()
                }
                this.dongTestList = [
                    {
                        test: {
                            title: '',
                            content: '',
                        }

                    }
                ]
                this.testList = []
            }).catch(() => {
                this.$message({
                    message: '操作取消',
                    type: 'info'
                })
            });

        },

        //点击确定将试题加入试题列表
        addTestList() {
            console.log('添加试题')
            let len = this.dongTestList.length
            for (let index = 0; index < len; index++) {
                this.$refs.testForm[index].validate((valid) => {
                    if (valid) {
                        if (index == len - 1) {
                            this.testList = []
                            for (let i = 0; i < len; i++) {
                                let tst = this.dongTestList[i]
                                // let ts = {
                                //     title: tst.title,
                                //     content: tst.content
                                // }
                                // console.log(ts)
                                this.testList.push(tst.test)
                            }
                            this.testDialog = false
                            this.add = true
                        }
                        // this.clearTestInfo()
                    } else {
                        this.$message({
                            message: '还有非空试题，不能提交哦*~*',
                            type: 'error'
                        })
                        return false;
                    }
                })

            }
        },

        //动态新增一条试题编辑项
        addATest() {
            let len = this.dongTestList.length
            if (len >= 50) {
                this.$message({
                    message: '题目数量已达最大',
                    type: 'warning'
                })
                return;
            }
            this.dongTestList.push({
                test: {
                    title: '',
                    content: ''
                }
            })
        },

        //图片上传成功
        handleSuccess(res) {
            console.log(res)
            this.heartMark.img = res.message
        },

        //点击添加试题
        clickAddTest() {
            this.add = false
            this.testDialog = true
        },

        //删除一条试题
        deleteATest(item) {
            this.$confirm('确定删除该试题吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (this.dongTestList.length < 2) {
                    this.$message({
                        message: '不能再删了~~',
                        type: 'warning'
                    })
                    return
                }

                let ind = this.dongTestList.lastIndexOf(item)
                console.log(ind)
                this.dongTestList.splice(ind, 1)
            }).catch(() => {
                this.$message({
                    message: '操作取消',
                    type: 'info'
                })
            });
        },




    },
    mounted() {
        this.queryList()
    }
}
</script>

<style scoped>
.test-row {
    margin-bottom: 20px;
}
</style>